<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退货单号" prop="srCode">
        <el-input
          v-model="queryParams.srCode"
          placeholder="请输入退货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据状态" prop="srState">
        <el-input
          v-model="queryParams.srState"
          placeholder="请输入单据状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售日期" prop="saleDate">
        <el-date-picker clearable
          v-model="queryParams.saleDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择销售日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户名称" prop="customer">
        <el-input
          v-model="queryParams.customer"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['rejected:rejected:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['rejected:rejected:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['rejected:rejected:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['rejected:rejected:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-check"
          size="mini"
          :disabled="single"
          @click="handlecheck"
          v-hasPermi="['rejected:rejected:check']"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleClose"
          v-hasPermi="['rejected:rejected:close']"
        >关闭</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-dialog title="审核" :visible.sync="shopen" width="500px">
      <el-form :model="shform">
        <el-form-item label="审核结果" prop="result">
          <el-radio-group v-model="shform.result">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="1">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="comments">
          <el-input type="textarea" v-model="shform.comments" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="shopen = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table v-loading="loading" :data="rejectedList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号 " align="center" prop="srId" fixed="left"/>
      <el-table-column label="退货单号" align="center" prop="" width="180" fixed="left">
        <template #default="scope">
          <router-link :to="{ path:'/wms/rejected/rejected/detail',query:{rejected:scope.row}}">{{ scope.row.srCode }}</router-link>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="srState" fixed="left">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.py_status" :value="scope.row.srState"/>
        </template>
      </el-table-column>
      <el-table-column label="销售单号" align="center" prop="saleCode" width="180" fixed="left"/>
      <el-table-column label="销售日期" align="center" prop="saleDate" width="180" fixed="left">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customer"  fixed="left"/>
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="联系方式" align="center" prop="phone" width="180"/>
      <el-table-column label="销售部门" align="center" prop="saleDept" />
      <el-table-column label="销售负责人" align="center" prop="salePerson" width="150"/>
      <el-table-column label="退货数量" align="center" prop="rejectedNum" />
      <el-table-column label="退货金额" align="center" prop="rejectedMoney" />
      <el-table-column label="退货商品" align="center"  width="280">
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.proNames" placement="top">
            <div>{{ changeProNames(scope.row.proNames) }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="createBy" />
      <el-table-column label="所在部门" align="center" prop="createDept" />
      <el-table-column label="制单时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="reviewer" />
      <el-table-column label="审核时间" align="center" prop="reviewerTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reviewerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="['2'].includes(scope.row.srState)"
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="handleRevoke(scope.row)"
            v-hasPermi="['rejected:rejected:revoke']"
          >撤销</el-button>
          <el-button
            size="mini"
            type="text"
            v-if="['0', '1'].includes(scope.row.srState)"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['rejected:rejected:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            v-if="['0', '1'].includes(scope.row.srState)"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['rejected:rejected:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售退货对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="退货单号" prop="srCode">
          <el-input v-model="form.srCode" placeholder="请输入退货单号" />
        </el-form-item>
        <el-form-item label="单据状态" prop="srState">
          <el-input v-model="form.srState" placeholder="请输入单据状态" />
        </el-form-item>
        <el-form-item label="销售单号" prop="saleCode">
          <el-input v-model="form.saleCode" placeholder="请输入销售单号" />
        </el-form-item>
        <el-form-item label="销售日期" prop="saleDate">
          <el-date-picker clearable
            v-model="form.saleDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择销售日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户名称" prop="customer">
          <el-input v-model="form.customer" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="销售部门" prop="saleDept">
          <el-input v-model="form.saleDept" placeholder="请输入销售部门" />
        </el-form-item>
        <el-form-item label="销售负责人" prop="salePerson">
          <el-input v-model="form.salePerson" placeholder="请输入销售负责人" />
        </el-form-item>
        <el-form-item label="退货原因" prop="rejectedReason">
          <el-input v-model="form.rejectedReason" placeholder="请输入退货原因" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-divider content-position="center">${subTable.functionName}信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddOdSaleRejectedDetails">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOdSaleRejectedDetails">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="odSaleRejectedDetailsList" :row-class-name="rowOdSaleRejectedDetailsIndex" @selection-change="handleOdSaleRejectedDetailsSelectionChange" ref="odSaleRejectedDetails">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="货品名称" prop="productName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productName" placeholder="请输入货品名称" />
            </template>
          </el-table-column>
          <el-table-column label="货品编号" prop="productCode" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productCode" placeholder="请输入货品编号" />
            </template>
          </el-table-column>
          <el-table-column label="货品类型" prop="productType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.productType" placeholder="请选择货品类型">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" prop="productModel" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.productModel" placeholder="请输入规格型号" />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" />
            </template>
          </el-table-column>
          <el-table-column label="销售数量" prop="saleNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.saleNum" placeholder="请输入销售数量" />
            </template>
          </el-table-column>
          <el-table-column label="本次退货数量" prop="rejectedNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.rejectedNum" placeholder="请输入本次退货数量" />
            </template>
          </el-table-column>
          <el-table-column label="已出库" prop="notyetNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.notyetNum" placeholder="请输入已出库" />
            </template>
          </el-table-column>
          <el-table-column label="销售单价" prop="salePrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.salePrice" placeholder="请输入销售单价" />
            </template>
          </el-table-column>
          <el-table-column label="退货金额" prop="rejectedPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.rejectedPrice" placeholder="请输入退货金额" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <el-table-column label="逻辑删除" prop="isDel" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.isDel" placeholder="请输入逻辑删除" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRejected, getRejected, delRejected, addRejected, updateRejected,checkbyId,revokebyId,colseById } from "@/api/rejected/rejected";
import item from "@/layout/components/Sidebar/Item.vue";

export default {
  name: "Rejected",
  dicts: ['py_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      se:[],
      // 子表选中数据
      checkedOdSaleRejectedDetails: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售退货表格数据
      rejectedList: [],
      // ${subTable.functionName}表格数据
      odSaleRejectedDetailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      shopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        srCode: null,
        srState: null,
        saleDate: null,
        customer: null,
      },
      // 表单参数
      form: {},
      shform:{
        srId: null
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询销售退货列表 */
    getList() {
      this.loading = true;
      listRejected(this.queryParams).then(response => {
        console.log("销售退货详情："+response.rows);
        this.rejectedList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        srId: null,
        srCode: null,
        srState: null,
        saleCode: null,
        saleDate: null,
        customer: null,
        contacts: null,
        phone: null,
        saleDept: null,
        salePerson: null,
        rejectedNum: null,
        rejectedMoney: null,
        rejectedReason: null,
        remark: null,
        createBy: null,
        createDept: null,
        createTime: null,
        reviewer: null,
        reviewerReport: null,
        reviewerTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null
      };
      this.odSaleRejectedDetailsList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.srId)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.se=selection.map(item=>item.srState);

    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push( {path:'/wms/rejected/rejected/add'});
      /*this.reset();
      this.open = true;
      this.title = "添加销售退货";*/
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const srId = row.srId || this.ids;
      const srState = row.srState || this.se;
     // alert(srState)
      if (srState==0 || srState==1 ){
        this.$router.push( {path:'/wms/rejected/rejected/update',
          query:{
            id: srId
          }})
      }else{
        this.$modal.msgError("该单据不能修改");
        return;
      }
      /*getRejected(srId).then(response => {
        this.form = response.data;
        this.odSaleRejectedDetailsList = response.data.odSaleRejectedDetailsList;
        this.open = true;
        this.title = "修改销售退货";
      });*/
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.odSaleRejectedDetailsList = this.odSaleRejectedDetailsList;
          if (this.form.srId != null) {
            updateRejected(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRejected(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const srIds = row.srId || this.ids;
      if(this.se=='3' ){
        this.$modal.msgError("该单据正在执行，不能删除");
        return;
      }else {
        this.$modal.confirm('是否确认删除销售退货编号为"' + srIds + '"的数据项？').then(function() {
          return delRejected(srIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
	/** ${subTable.functionName}序号 */
    rowOdSaleRejectedDetailsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** ${subTable.functionName}添加按钮操作 */
    handleAddOdSaleRejectedDetails() {
      let obj = {};
      obj.productName = "";
      obj.productCode = "";
      obj.productType = "";
      obj.productModel = "";
      obj.unit = "";
      obj.saleNum = "";
      obj.rejectedNum = "";
      obj.notyetNum = "";
      obj.salePrice = "";
      obj.rejectedPrice = "";
      obj.remark = "";
      obj.isDel = "";
      this.odSaleRejectedDetailsList.push(obj);
    },
    /** ${subTable.functionName}删除按钮操作 */
    handleDeleteOdSaleRejectedDetails() {
      if (this.checkedOdSaleRejectedDetails.length == 0) {
        this.$modal.msgError("请先选择要删除的${subTable.functionName}数据");
      } else {
        const odSaleRejectedDetailsList = this.odSaleRejectedDetailsList;
        const checkedOdSaleRejectedDetails = this.checkedOdSaleRejectedDetails;
        this.odSaleRejectedDetailsList = odSaleRejectedDetailsList.filter(function(item) {
          return checkedOdSaleRejectedDetails.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleOdSaleRejectedDetailsSelectionChange(selection) {
      this.checkedOdSaleRejectedDetails = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rejected/rejected/export', {
        ...this.queryParams
      }, `rejected_${new Date().getTime()}.xlsx`)
    },
    handlecheck(){
      if (this.se!='0'){
        this.$modal.msgError("该单据无需审核");
        return;
      }else {
        this.shopen=true;
      }
    },
    handleSubmit(){
      this.shform.srId=this.ids;
      console.log("审核",this.shform);
      checkbyId(this.shform).then(response => {
        this.getList();
        this.shopen=false;
        this.$modal.msgSuccess("已审核");
      })
    },
    handleRevoke(row){
      const  srId=row.srId
     // alert(srId)
      this.$confirm('是否撤回所选单据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        revokebyId(srId).then(respnse=>{
          this.getList();
          this.$message({
            type: 'success',
            message: '撤销成功!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '撤销删除'
        });
      });
    },
    handleClose(){
      const srId=this.ids;
     // alert(srId)
      if(this.se=='3'){
        this.$modal.msgError("该单据无发关闭");
        return;
      }else {
        this.$confirm('是否关闭所选单据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          colseById(srId).then(respnse=>{
            this.getList();
            this.$message({
              type: 'success',
              message: '关闭成功!'
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '关闭删除'
          });
        });
      }

    },
    changeProNames(value){
      var arr = [];
      if (typeof value === 'string') {
        arr = value.split(",");
      } else if (Array.isArray(value)) {
        arr = value;
      } else {
        console.error("Invalid type for value:", value);
        arr = [];
      }
      // 如果数组长度小于或等于3，直接连接数组元素
      if (arr.length <= 2) {
        return arr.join('、');
      }
      // 如果数组长度大于3，取前三个元素，然后添加"等X项……"，其中X是数组长度
      var firstThree = arr.slice(0, 2);
      var restCount = arr.length-1;
      return firstThree.join('、') + '等' + restCount + '项……';
    }
  }
};
</script>
